module Payers
  class RegistrationsController < ApplicationController

    def create
      return unless verify_verification_code('register')
      payer = Payer.new(registration_params)
      if payer.save
        head :no_content
      else
        render json: payer.errors, status: :unprocessable_entity
      end
    end

    def update
      return unless verify_verification_code('reset_password')
      payer = Payer.find_by(params.permit(:mobile))
      payer.password = params[:password]
      payer.save
      head :no_content
    end

    private

    def registration_params
      params.permit(:mobile, :password)
    end

    def verify_verification_code(usage)
      code = params.require(:verification_code)
      verification_code = VerificationCode.where(mobile: params.require(:mobile), usage: usage)
                              .where('expires_at >= ?', Time.now)
                              .first

      if verification_code&.code == code
        true
      else
        render json: {verification_code: [t('errors.messages.invalid')]}, status: :unprocessable_entity
        false
      end
    end
  end
end